import { LoginApi, RegisterApi } from '@/api';
import React, { useState } from 'react';
import logo from '@/assets/images/logo.png';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import './login.less';
import { useNavigate } from 'react-router-dom';
import { useToast } from '@/util/toast';

export default function Login() {
  // 写一个标记，记录当前是登录还是注册
  const [isLoginPage, setIsLoginPage] = useState(true);
  // 用户名和密码
  const [username, setUserName] = useState('12345678901');
  const [password, setPassword] = useState('wolfcode123');
  const toast = useToast();

  // 获取跳转的方法
  const navigate = useNavigate();
  const login = () => {
    LoginApi({
      password,
      username,
    }).then((res) => {
      if (res.errCode === 0) {
        localStorage.setItem('token', res.data);
        toast('success', '登录成功');
        // 跳转到首页
        navigate('/home');
      }
    });
  };

  const register = () => {
    // 在这个里面写注册的逻辑
    RegisterApi({
      phone: username,
      password,
    }).then((res) => {
      if (res.errCode === 0) {
        toast('success', '注册成功');
        // 去登录
        setIsLoginPage(true);
      }
    });
  };

  const btnClick = () => {
    // 验证数据的完整性
    // 用户名，密码是否为空
    // 手机号的格式是否正确
    isLoginPage ? login() : register();
  };
  return (
    <div className="login">
      <img src={logo} alt="" />
      <section className="form">
        <TextField
          variant="outlined"
          placeholder="请输入手机号"
          value={username}
          onChange={(e) => setUserName(e.target.value)}
        />
        <TextField
          variant="outlined"
          type="password"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <Button onClick={btnClick} variant="contained">
          {isLoginPage ? '登录' : '注册'}
        </Button>
      </section>
      <div className="exchange">
        <span onClick={() => setIsLoginPage(!isLoginPage)}>
          去{isLoginPage ? '注册' : '登录'}
        </span>
      </div>
    </div>
  );
}
